const express = require('express')
const router = express.Router()
const db = require('../../../MySql')
const { formatDateTime } = require('../../utils/dateUtils')
const { generate19DigitId } = require('../../utils/idUtils')
const el_qu_answer = require('../../models/el_qu_answer')
const el_qu_repo = require('../../models/el_qu_repo')



router.post('/qu/qu/paging', async (req, res) => {
    try {
        const rawQuType = req.body?.params?.quType
        const quType = (!rawQuType && rawQuType !== 0) ? '' : rawQuType

        const rawContent = req.body?.params?.content
        const content = (!rawContent && rawContent !== 0) ? '' : rawContent

        const repoIds = req.body?.params?.repoIds || []

        // 构建SQL查询
        let sql = 'SELECT * FROM el_qu WHERE 1=1'
        let params = []
        let countSql = 'SELECT COUNT(*) as total FROM el_qu WHERE 1=1'
        let countParams = []

        // 添加题库ID条件（支持多个题库）
        if (repoIds.length > 0) {
            // 查询el_qu_repo表的qu_id，在el_qu表中查询对应题目
            const placeholders = repoIds.map(() => '?').join(',')
            sql += ` AND id IN (SELECT qu_id FROM el_qu_repo WHERE repo_id IN (${placeholders}))`
            countSql += ` AND id IN (SELECT qu_id FROM el_qu_repo WHERE repo_id IN (${placeholders}))`
            params.push(...repoIds)
            countParams.push(...repoIds)
        }

        // 添加题目类型条件
        if (quType) {
            sql += ' AND qu_type = ?'
            countSql += ' AND qu_type = ?'
            params.push(quType)
            countParams.push(quType)
        }

        // 添加内容搜索条件
        if (content) {
            sql += ' AND content LIKE ?'
            countSql += ' AND content LIKE ?'
            params.push(`%${content}%`)
            countParams.push(`%${content}%`)
        }

        // 添加分页
        sql += ' order by create_time desc'
        const pageSize = parseInt(req.body.size) || 10
        const currentPage = parseInt(req.body.current) || 1
        const offset = (currentPage - 1) * pageSize
        sql += ' LIMIT ? OFFSET ? '
        params.push(pageSize, offset)

        // 执行查询
        const [countResult] = await db.query(countSql, countParams)
        const [results] = await db.query(sql, params)

        const records = results.map(item => ({
            id: item.id,
            quType: item.qu_type,
            level: item.level,
            image: item.image,
            content: item.content,
            createTime: formatDateTime(item.create_time),
            updateTime: formatDateTime(item.update_time),
            remark: item.remark,
            analysis: item.analysis,
        }))

        return res.json({
            "msg": "操作成功！",
            "code": 0,
            "data": {
                "records": records,
                "total": countResult[0].total,
                "size": pageSize,
                "current": currentPage,
                "orders": [],
                "optimizeCountSql": true,
                "hitCount": false,
                "searchCount": true,
                "pages": Math.ceil(countResult[0].total / pageSize)
            },
            "success": true
        })
    } catch (error) {
        console.error("查询失败:", error)
        return res.status(500).json({
            msg: "数据库查询失败",
            code: 500,
            success: false
        })
    }
})


router.post('/qu/qu/detail', async (req, res) => {
    try {
        const { id } = req.body

        const [results] = await db.query(`select * from el_qu where id = ?`, [id])

        // 查询试题答案
        // const [answerListRes] = await db.query(
        //     `select * from el_qu_answer where qu_id = ? `,
        //     [id]
        // )
        const answerListRes = await el_qu_answer.findQuAnswerByQuId(id)

        // 查询试题所属题库
        // const [repoIdsRes] = await db.query(
        //     `select repo_id from el_qu_repo where qu_id = ?`,
        //     [id]
        // )
        const repoIdsRes = await el_qu_repo.findQuRepoByQuId(id)


        const answerList = answerListRes.map(item => ({
            id: item.id,
            quId: item.qu_id,
            isRight: item.is_right === 1,
            image: item.image || "",
            content: item.content || "",
            analysis: item.analysis || ""
        }))

        const repoIds = repoIdsRes.map(item => item.repo_id)

        return res.json({
            "msg": "操作成功！",
            "code": 0,
            "data": {
                "id": results[0].id,
                "quType": results[0].qu_type,
                "level": results[0].level,
                "image": results[0].image,
                "content": results[0].content,
                "createTime": formatDateTime(results[0].create_time),
                "updateTime": formatDateTime(results[0].update_time),
                "remark": results[0].remark,
                "analysis": results[0].analysis,
                "answerList": answerList,
                "repoIds": repoIds
            },
            "success": true
        })
    } catch (error) {
        console.error(error)
        return res.status(500).json({
            msg: 'Internal server error',
            code: 500,
            success: false
        })
    }
})

router.post('/qu/qu/save', async (req, res) => {
    const connection = await db.getConnection()
    try {
        await connection.beginTransaction()

        const {
            id,
            quType,
            level,
            image,
            content,
            remark,
            analysis,
            answerList,
            repoIds
        } = req.body

        const currentTime = new Date()

        if (id) {
            // 更新试题
            await connection.query(
                `UPDATE el_qu SET qu_type = ?, level = ?, image = ?, content = ?, 
                 remark = ?, analysis = ?, update_time = ? WHERE id = ?`,
                [quType, level, image, content, remark, analysis, currentTime, id]
            )

            // 删除原有答案
            await connection.query(
                'DELETE FROM el_qu_answer WHERE qu_id = ?',
                [id]
            )

            // 删除原有题库关联
            await connection.query(
                'DELETE FROM el_qu_repo WHERE qu_id = ?',
                [id]
            )
        } else {
            // 新增试题
            const newId = generate19DigitId()
            await connection.query(
                `INSERT INTO el_qu (id, qu_type, level, image, content, 
                 remark, analysis, create_time, update_time) 
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
                [newId, quType, level, image || '', content, remark || '', analysis || '', currentTime, currentTime]
            )
            req.body.id = newId
        }

        // 插入答案选项
        if (answerList && answerList.length > 0) {
            const answerValues = answerList.map((answer, index) => [
                //generate19DigitId(),
                req.body.id,
                answer.isRight ? 1 : 0,
                answer.image || '',
                answer.content || '',
                answer.analysis || '',
            ])

            await connection.query(
                `INSERT INTO el_qu_answer (qu_id, is_right, image, content, analysis)  VALUES ?`,
                [answerValues]
            )
        }

        // 插入题库关联
        if (repoIds && repoIds.length > 0) {
            const repoValues = []

            for (const repoId of repoIds) {
                // 查询该题库中已有的题目数量
                const [countRes] = await connection.query(
                    'SELECT COUNT(*) as count FROM el_qu_repo WHERE repo_id = ?',
                    [repoId]
                )
                const currentCount = countRes[0].count

                repoValues.push([
                    generate19DigitId(),
                    req.body.id,
                    repoId,
                    quType,
                    currentCount + 1  // 在已有题目数量基础上+1
                ])
            }

            await connection.query(`INSERT INTO el_qu_repo (id, qu_id, repo_id, qu_type, sort) VALUES ?`, [repoValues])
        }

        await connection.commit()

        return res.json({
            "msg": "保存成功！",
            "code": 0,
            "success": true,
            "data": {
                "id": req.body.id
            }
        })
    } catch (error) {
        await connection.rollback()
        console.error('保存试题失败:', error)
        return res.status(500).json({
            msg: '保存失败',
            code: 500,
            success: false
        })
    } finally {
        connection.release()
    }
})


router.post('/qu/qu/delete', async (req, res) => {
    try {
        const { ids } = req.body

        if (!ids || ids.length === 0) {
            return res.status(400).json({
                msg: '请提供要删除的试题ID列表',
                code: 400,
                success: false
            })
        }

        // 删除试题关联
        await db.query(
            'DELETE FROM el_qu_repo WHERE qu_id IN (?)',
            [ids]
        )

        // 删除答案选项
        await db.query(
            'DELETE FROM el_qu_answer WHERE qu_id IN (?)',
            [ids]
        )

        // 删除试题
        await db.query(
            'DELETE FROM el_qu WHERE id IN (?)',
            [ids]
        )

        return res.json({
            "msg": "删除成功！",
            "code": 0,
            "success": true
        })

    } catch (error) {
        console.error('删除试题失败:', error)
        return res.status(500).json({
            msg: '删除失败',
            code: 500,
            success: false
        })
    }
})



module.exports = router;